<template>
  <div class="page-container">
    <el-card class="content-container">
      <div class="toolbar">
        <div class="toolbar-left">
          <h3>订单管理</h3>
        </div>
      </div>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.nongchanpinOrderUuidNumber" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.nongchanpinOrderTypes" placeholder="请选择状态" clearable>
            <el-option label="已支付" value="1" />
            <el-option label="退款" value="2" />
            <el-option label="已发货" value="3" />
            <el-option label="已收货" value="4" />
            <el-option label="已评价" value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="(rows)=>selectedRows=rows"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="nongchanpinOrderUuidNumber" label="订单编号" />
        <el-table-column prop="nongchanpinName" label="商品名称" />
        <el-table-column prop="buyNumber" label="购买数量" width="100" />
        <el-table-column prop="nongchanpinOrderTruePrice" label="实付金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.nongchanpinOrderTruePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="yonghuName" label="买家" />
        <el-table-column prop="shangjiaName" label="商家" />
        <el-table-column label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.nongchanpinOrderTypes)">
              {{ scope.row.nongchanpinOrderValue || getStatusText(scope.row.nongchanpinOrderTypes) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">
              查看
            </el-button>
            <el-button
              v-if="scope.row.nongchanpinOrderTypes === 1"
              type="success"
              size="small"
              @click="handleShip(scope.row)"
            >发货</el-button>
            <el-button
              v-if="scope.row.nongchanpinOrderTypes === 1 || scope.row.nongchanpinOrderTypes === 3"
              type="warning"
              size="small"
              @click="handleRefund(scope.row)"
            >退款</el-button>
            <el-button
              v-if="scope.row.nongchanpinOrderTypes === 3"
              type="primary"
              size="small"
              @click="handleReceive(scope.row)"
            >收货</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 订单详情对话框 -->
      <el-dialog v-model="detailDialog.visible" title="订单详情" width="800px">
        <div v-if="orderDetail" class="order-detail">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-section">
                <h4>订单信息</h4>
                <p><strong>订单编号：</strong>{{ orderDetail.nongchanpinOrderUuidNumber }}</p>
                <p><strong>订单状态：</strong>
                  <el-tag :type="getStatusType(orderDetail.nongchanpinOrderTypes)">
                    {{ orderDetail.nongchanpinOrderValue || getStatusText(orderDetail.nongchanpinOrderTypes) }}
                  </el-tag>
                </p>
                <p><strong>下单时间：</strong>{{ orderDetail.createTime }}</p>
                <p><strong>实付金额：</strong>¥{{ orderDetail.nongchanpinOrderTruePrice }}</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-section">
                <h4>商品信息</h4>
                <p><strong>商品名称：</strong>{{ orderDetail.nongchanpinName }}</p>
                <p><strong>购买数量：</strong>{{ orderDetail.buyNumber }}</p>
                <p><strong>单价：</strong>¥{{ orderDetail.nongchanpinNewMoney }}</p>
                <p><strong>商家：</strong>{{ orderDetail.shangjiaName }}</p>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="12">
              <div class="detail-section">
                <h4>买家信息</h4>
                <p><strong>买家姓名：</strong>{{ orderDetail.yonghuName }}</p>
                <p><strong>联系电话：</strong>{{ orderDetail.yonghuPhone }}</p>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-section">
                <h4>收货地址</h4>
                <p><strong>收货人：</strong>{{ orderDetail.addressName }}</p>
                <p><strong>联系电话：</strong>{{ orderDetail.addressPhone }}</p>
                <p><strong>详细地址：</strong>{{ orderDetail.addressDizhi }}</p>
              </div>
            </el-col>
          </el-row>
        </div>
        <template #footer>
          <el-button @click="detailDialog.visible = false">关闭</el-button>
        </template>
      </el-dialog>

      <!-- 操作区 -->
      <div style="margin-top: 8px; display:flex; justify-content: space-between; align-items:center;">
        <div>
          <el-button
            v-if="selectedRows.length>0"
            type="danger"
            size="small"
            @click="handleBatchDelete"
          >批量删除</el-button>
        </div>
        <!-- 分页 -->
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'

let selectedRows = ref([])

import { ElMessage, ElMessageBox } from 'element-plus'

const instance = getCurrentInstance()
const http = instance?.proxy?.$http

// 响应式数据
const loading = ref(false)
const tableData = ref([])

const searchForm = reactive({
  nongchanpinOrderUuidNumber: '',
  nongchanpinOrderTypes: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 订单详情对话框
const detailDialog = reactive({ visible: false })
const orderDetail = ref(null)

// 方法
const getStatusType = (status) => {
  const statusMap = {
    1: 'warning',  // 已支付
    2: 'danger',   // 退款
    3: 'primary',  // 已发货
    4: 'success',  // 已收货
    5: 'info'      // 已评价
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '已支付',
    2: '退款',
    3: '已发货',
    4: '已收货',
    5: '已评价'
  }
  return statusMap[status] || '未知'
}

const loadData = async () => {
  if (!http) {
    ElMessage.error('系统初始化失败，请刷新页面重试')
    return
  }
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.size,
      ...searchForm
    }
    const res = await http({
      url: '/nongchanpinOrder/page',
      method: 'get',
      params
    })
    if (res.code === 0) {
      tableData.value = res.data.list || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.msg || '加载订单数据失败')
    }
  } catch (e) {
    console.error('加载订单数据失败', e)
    ElMessage.error('加载订单数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

const handleView = async (row) => {
  try {
    const res = await http({
      url: `/nongchanpinOrder/info/${row.id}`,
      method: 'get'
    })
    if (res.code === 0) {
      orderDetail.value = res.data
      detailDialog.visible = true
    } else {
      ElMessage.error(res.msg || '获取订单详情失败')
    }
  } catch (e) {
    console.error('获取订单详情失败', e)
    ElMessage.error('获取订单详情失败')
  }
}

const handleShip = async (row) => {
  await updateOrderStatus(row, 3, '已发货')
}

const handleRefund = async (row) => {
  await updateOrderStatus(row, 2, '已退款')
}

const handleReceive = async (row) => {
  await updateOrderStatus(row, 4, '已收货')
}

async function updateOrderStatus(row, status, msg) {
  try {
    const res = await http({
      url: '/nongchanpinOrder/update',
      method: 'post',
      data: { id: row.id, nongchanpinOrderTypes: status }
    })
    if (res.code === 0) {
      ElMessage.success(`订单 ${row.nongchanpinOrderUuidNumber} ${msg}`)
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (e) {
    console.error('订单操作失败', e)
    ElMessage.error('操作失败')
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

const handleBatchDelete = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedRows.value.length} 条订单记录吗？`,
      '批量删除',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    )
    const ids = selectedRows.value.map(r => r.id)
    const res = await http({ url: '/nongchanpinOrder/delete', method: 'post', data: { ids } })
    if (res.code === 0) {
      ElMessage.success('批量删除成功')
      loadData()
    } else {
      ElMessage.error(res.msg || '批量删除失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('批量删除失败', e)
      ElMessage.error('批量删除失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
@import '@/styles/index.scss';

.order-detail {
  .detail-section {
    margin-bottom: 20px;

    h4 {
      margin-bottom: 10px;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 5px;
    }

    p {
      margin: 8px 0;
      line-height: 1.6;
    }
  }
}
</style>
